package com.ccteam.shared.domain.moment

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_NONE
import com.ccteam.model.moment.MomentShareVO
import com.ccteam.shared.api.UserDataSource
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.moment.MomentsUserPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.moment.MomentListItem
import com.ccteam.shared.result.user.MeHomeInfoItem
import com.ccteam.shared.utils.ALBUM_QUALITY
import com.ccteam.shared.utils.EMPTY_STRING
import com.ccteam.shared.utils.MOMENT_QUALITY
import com.ccteam.shared.utils.PHOTO_QUALITY
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/7
 *
 * 用户个人的朋友圈Domain层
 */
class MomentInfoUserDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val userDataSource: UserDataSource
): PagingUseCase<MeHomeInfoItem?, MomentListItem>(
    Dispatchers.IO
) {
    override fun execute(parameters: MeHomeInfoItem?): Flow<PagingData<MomentListItem>> {
        val userInfo = userCore.userInfo.value
        val isLogin = userCore.isLogin.value

        if(!isLogin ||
            userInfo.userToken.isNullOrEmpty()
            || userInfo.userId.isNullOrEmpty() || parameters == null){
            return flowOf(PagingData.empty())
        }
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            MomentsUserPagingSource(userInfo.userToken,parameters.userId,userDataSource)
        }.flow.map { pagingData ->
            pagingData.map {
                MomentListItem(it.id,parameters.userId,
                    parameters.userName,
                    parameters.userPhotoUrl + PHOTO_QUALITY,
                    it.createTime,it.content, it.images.map { momentImage ->
                        MomentListItem.MomentImageItem(momentImage.id,momentImage.momentId,momentImage.url + MOMENT_QUALITY)
                    },
                    transformToMomentShareItem(it.momentShareVO,it.type,it.shareId),it.upNum,it.commentNum)
            }
        }
    }

    private fun transformToMomentShareItem(momentShareVO: MomentShareVO?,
                                           type: Int, shareId: String?): MomentListItem.MomentShareItem?{
        if(type == MOMENT_SHARE_TYPE_NONE || momentShareVO == null || shareId == null){
            return null
        }
        return MomentListItem.MomentShareItem(
            shareId,type,momentShareVO.title ?: EMPTY_STRING,
            momentShareVO.subTitle ?: EMPTY_STRING,
            momentShareVO.imgUrl + ALBUM_QUALITY
        )

    }
}